const router = require('koa-router')()
const { exec } = require('../db/index')
const jwt = require('jsonwebtoken')
const { SuccessModel, FailModel } = require('../utils/resModel')
const { secret } = require('../config')
const { getPassword } = require('../utils/crypto')

router.prefix('/users')

// 授权登陆中间件
const auth = async (ctx, next) => {
 /**
  * 1. 拿到token
  * 2. 解析token { id,username, password }
  * 3. 存在一个变量中 ctx.state.user = user;
  */
  const { token = '' } = ctx.request.header;
  try {
    // 验证账号密码
    const user = jwt.verify(token, secret)
    ctx.state.user = user // 
  } catch(err) {
    // 如果不成功，就把控制权教给错误抛出
    ctx.throw(401, '未授权登陆，请登录')
  }
  await next() // 如果成功就把控制权教给下一个了
}

// 权限认证  只有id=1 才能删除
const checkOwner = async (ctx, next) => {
   /**
    * 1. 找到id   ctx.state.user.id
    * 2. 判断id是否具有权限  ID = 1
    */
   const { id } = ctx.state.user;
   if (id === 1) {
     await next()
   } else {
     ctx.throw(402, '权限不足，请联系管理员')
   }
}

router.get('/get-test', async (ctx, next) => {
  ctx.body = {
    msg: 'success'
  }
})

// 注册功能 query request.body params  header
router.post('/register', async(ctx, next) => {
  ctx.verifyParams({
    username: { type: 'string', require: true },
    password: { type: 'string', require: true },
    realname: { type: 'string', require: true }
  })
  // 
  const { username, password, realname } = ctx.request.body;
  const sql = `insert into loginusers (username, password, realname) values ('${username}', '${getPassword(password)}', '${realname}');`
  const data = await exec(sql)
  ctx.body = new SuccessModel({
    insertId: data.insertId // 返回插入数据库的ID
  }, 'success')
})

// 登陆
router.post('/login', async(ctx, next) => {
  /** 
   * 1. 校验
   * 2. 查数据库
   * 3. const token = jwt.sign({ id, name, password }, secret, { expiresIn:'1h'}) 第三个参数是过期时间
   * 4. 返回token 
   * 
   * 
   * 将token返回给前端是为什么呢？
   * 
   * 主要就是让前端访问其他需要登陆的接口的时候，带上token
   * 
   */
  // 1. 校验
  ctx.verifyParams({
    username: { type: 'string', require: true },
    password: { type: 'string', require: true }
  })
  // 2. 查数据库
  const sql = `select * from loginusers where username='${ctx.request.body.username}' and password='${getPassword(ctx.request.body.password)}';`
  const data = await exec(sql);
  // 判断 用户名密码
  if (!data.length) { ctx.throw(401, '用户名或者密码错误了') }
  const { id, username, password } = data[0]
  // 3. token  设置过期时间
  const token = jwt.sign({ id, username, password }, secret, { expiresIn:'1h'})
  // 4. 返回token
  ctx.body = new SuccessModel({token}, '登陆成功')
})

// 增加  -  删除
router.delete('/:id', auth, checkOwner, async(ctx, next) => {
  const sql = `delete from loginusers where id = ${ctx.params.id};`
  // const data = await exec(sql)
  ctx.body = new SuccessModel( '删除成功了')
})


module.exports = router
